package my.sa;

import java.awt.*;
import java.awt.event.*;
import java.io.File;

import javax.swing.*;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

public class JavaStaticAnaly extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8709709281534767913L;
	
	private JTextPane infoText;

	public JavaStaticAnaly() {
		super("Java静态分析");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// String laf = UIManager.getCrossPlatformLookAndFeelClassName();
		String laf = UIManager.getSystemLookAndFeelClassName();
		try {
			UIManager.setLookAndFeel(laf);
		} catch (UnsupportedLookAndFeelException exc) {
			System.err.println("Warning: UnsupportedLookAndFeel: " + laf);
		} catch (Exception exc) {
			System.err.println("Error loading " + laf + ": " + exc);
		}

		JLabel label1 = new JLabel("文件路径:");
		final JTextField filePathText = new JTextField("选择文件", 20);
		//filePathText.setEditable(false);
		JButton fileChooseButton = new JButton("选择文件");
		final JButton analyButton = new JButton("分析");

		infoText = new JTextPane();
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setViewportView(infoText);

		final JFileChooser fileChooser = new JFileChooser();

		fileChooser.setFileFilter(new FileFilter() {

			@Override
			public String getDescription() {
				return ".java文件";
			}

			@Override
			public boolean accept(File f) {
				return f.isDirectory() || f.getName().endsWith(".java");
			}
		});
		fileChooseButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int option = fileChooser.showOpenDialog(JavaStaticAnaly.this);
				if (option == JFileChooser.APPROVE_OPTION) {
					File file = fileChooser.getSelectedFile();
					filePathText.setText(file.getAbsolutePath());
				}
			}
		});

		analyButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String filePath = filePathText.getText();
				if (filePath != null && filePath.length() > 0
						&& filePath.endsWith(".java")) {
					File javaFile = new File(filePath);
					if (!javaFile.exists()) {
						JOptionPane.showMessageDialog(JavaStaticAnaly.this,
								"选择的Java文件不存在。","提示",JOptionPane.WARNING_MESSAGE);
						return;
					} else {
						analyButton.setEnabled(false);
						analy(javaFile);
						analyButton.setEnabled(true);
					}
				} else {
					JOptionPane.showMessageDialog(JavaStaticAnaly.this,
							"请选择需要分析的Java文件。","提示",JOptionPane.WARNING_MESSAGE);
				}

			}
		});
		Container c = getContentPane();
		GroupLayout layout = new GroupLayout(c);
		c.setLayout(layout);

		// 自动设定组件、组之间的间隙
		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);

		// LEADING -- 左对齐 BASELINE -- 底部对齐 CENTER -- 中心对齐
		ParallelGroup hpg = layout
				.createParallelGroup(GroupLayout.Alignment.CENTER);

		SequentialGroup hpg2 = layout.createSequentialGroup();
		hpg2.addGroup(layout.createSequentialGroup().addComponent(label1));
		hpg2.addGroup(layout.createSequentialGroup().addComponent(filePathText));
		hpg2.addGroup(layout.createSequentialGroup().addComponent(
				fileChooseButton));
		hpg2.addGroup(layout.createSequentialGroup().addComponent(analyButton));
		hpg.addGroup(hpg2).addComponent(scrollPane);

		SequentialGroup vpg = layout.createSequentialGroup();
		GroupLayout.ParallelGroup vpg2 = layout
				.createParallelGroup(GroupLayout.Alignment.BASELINE);
		vpg2.addComponent(label1).addComponent(filePathText)
				.addComponent(fileChooseButton).addComponent(analyButton);
		vpg.addGroup(vpg2).addGroup(
				layout.createSequentialGroup().addComponent(scrollPane));

		// 水平
		layout.setHorizontalGroup(hpg);

		// 设定两个Button在水平方向一样宽
		layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {
				fileChooseButton, analyButton });

		// 垂直
		layout.setVerticalGroup(vpg);
		setBounds(300, 300, 500, 450);
		// setLocation(200,200);
		// pack();
		setVisible(true);
	}

	public void analy(File file){
		String dirPath = getPath(file);
		String filePath = file.getAbsolutePath();
		String compileInfo = getCompileInfo(filePath);
		StringBuilder info = new StringBuilder();
		if(null == compileInfo){
			showInfo("分析失败！\r\n请检查Path设置是否正确，文件否存在 ！",1);
		}else if(!"".equals(compileInfo)){
			showInfo("语法分析,错误信息：\r\n"+compileInfo,1);
			
		}else{
			info.append("语法分析成功，文件信息：");
			info.append(anInfo(filePath));
			String classFilePath = dirPath + file.getName().replace(".java", ".class");
			info.append(getClassDetailInfo(classFilePath));
			showInfo(info.toString(),0);
		}
	}
	
	public void showInfo(String msg,int type){
		if(type>0){
			SimpleAttributeSet attrSet = new SimpleAttributeSet();
			StyleConstants.setForeground(attrSet, Color.red);
			try {
				infoText.getDocument().insertString(0, msg, attrSet);
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
		}else{
			infoText.setText(msg);
		}
	}
	
	public String getPath(File file){
		return file.getParent()+"/";
	}
	public String getCompileInfo(String filePath){
		Compile c = new Compile();
		return  c.compile(filePath);
	}
	
	public String anInfo(String filePath){
		AnnotionAnaly aa = new AnnotionAnaly(filePath);
		aa.analy();
		return aa.toString();
	}
	
	public String getClassDetailInfo(String file){
		ClassDetail cd = new ClassDetail(file);
		return cd.getClassDetail();
	}

	
	public static void main(String[] args) {
		new JavaStaticAnaly();
	}
}
